import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt


def obj2example(label, data):
    """
    将文件转为 example
    :param label:
    :param data:
    :return:
    """
    return tf.train.Example(features=tf.train.Features(feature={
        'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
        'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[data.tostring()]))
    }))


def example2features(example_serialized):
    """
    将example 转为 features
    :param example_serialized:
    :return:
    """
    return tf.parse_single_example(example_serialized, features={'label': tf.FixedLenFeature([], tf.int64),
                                                                 'data': tf.FixedLenFeature([], tf.string)})


def save_tfcord(file):
    """
    保存tfcord文件
    :param file:
    :return:
    """
    mnist = tf.contrib.learn.datasets.load_dataset("mnist")
    labels = mnist.train.labels
    images = mnist.train.images
    num_examples = mnist.train.num_examples

    examples = []
    for i in range(num_examples):
        examples.append(obj2example(labels[i], images[i]))

    with tf.python_io.TFRecordWriter(file) as write:
        for example in examples:
            write.write(example.SerializeToString())


def read_tfcord(file):
    """
    读取tfcord文件
    :param file:
    :return:
    """
    reader = tf.TFRecordReader()
    file_queue = tf.train.string_input_producer([file])
    _, serialized_example = reader.read(file_queue)
    features = example2features(serialized_example)
    lable = tf.cast(features['label'], tf.int64)
    data = tf.cast(features['data'], tf.string)

    with tf.Session() as sess:
        coordinator = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess, coordinator)
        for _ in range(100):
            print(sess.run(lable))
        coordinator.request_stop()
        coordinator.join(threads)


def image_read(file):
    """
    Gfile 读取文件
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.FastGFile(file, 'rb').read()

    with tf.Session() as sess:
        image_data = tf.image.decode_image(image_raw_data)
        plt.imshow(sess.run(image_data))
        plt.show()
        jpeg = tf.image.encode_jpeg(image_data)
        with tf.gfile.GFile('../data/image/xg-bk.jpg', 'wb') as f:
            f.write(sess.run(jpeg))


def image_resize(file):
    """
    图片的大小变化
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.FastGFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    # 将图片大小变化   method 是 0 剪切方式
    img_convert_jpg = tf.image.convert_image_dtype(img_data_jpg, tf.float32)
    img_resized_jpg = tf.image.resize_images(img_convert_jpg, [50, 200], method=0)
    with tf.Session() as sess:
        plt.imshow(img_resized_jpg.eval())
        plt.show()


def crop_images(file):
    """
    剪贴图片
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.FastGFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    #
    img_crop_jpg = tf.image.resize_image_with_crop_or_pad(img_data_jpg, 100, 100)
    img_central_jpg = tf.image.central_crop(img_data_jpg, 0.6)
    with tf.Session() as sess:
        f = plt.figure()
        axes = f.add_subplot(1, 2, 1)
        axes.imshow(img_crop_jpg.eval())

        axes = f.add_subplot(1, 2, 2)
        axes.imshow(img_central_jpg.eval())
        plt.show()


def flip_image(file):
    """
    图片翻转
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.FastGFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    # 上下翻转
    flip_up_down_image = tf.image.flip_up_down(img_data_jpg)

    # 左右翻转
    flip_left_right_image = tf.image.flip_left_right(img_data_jpg)

    # 对角线翻转
    transpose_image = tf.image.transpose_image(img_data_jpg)

    # 随机上下翻转
    random_flip_up_down_image = tf.image.random_flip_up_down(img_data_jpg)

    # 随机左右翻转
    random_flip_left_right_image = tf.image.random_flip_left_right(img_data_jpg)

    with tf.Session() as sess:

        f = plt.figure()
        axes = f.add_subplot(2, 3, 1)
        axes.imshow(flip_up_down_image.eval())

        axes = f.add_subplot(2, 3, 2)
        axes.imshow(flip_left_right_image.eval())

        axes = f.add_subplot(2, 3, 3)
        axes.imshow(transpose_image.eval())

        axes = f.add_subplot(2, 3, 4)
        axes.imshow(random_flip_up_down_image.eval())

        axes = f.add_subplot(2, 3, 5)
        axes.imshow(random_flip_left_right_image.eval())

        plt.show()


def brightness_image(file):
    """
    调整图片亮度
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.GFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    # 将图片亮度调整 -0.5
    adjust_brightness_image = tf.image.adjust_brightness(img_data_jpg, -0.5)

    # 将图片亮度随机调整     左右区间为2
    random_brightness_image = tf.image.random_brightness(adjust_brightness_image, 2)

    with tf.Session() as sess:

        f = plt.figure()
        axes = f.add_subplot(2, 1, 1)
        axes.imshow(adjust_brightness_image.eval())

        axes = f.add_subplot(2, 1, 2)
        axes.imshow(random_brightness_image.eval())

        plt.show()


def contrast_images(file):
    """
    对比度调整
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.GFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    # 调整对比度
    contrast_image = tf.image.adjust_contrast(img_data_jpg, 0.5)

    # 随机调整对比度
    random_contrast_image = tf.image.random_contrast(img_data_jpg, 1, 3)
    with tf.Session() as sess:
        f = plt.figure()
        axes = f.add_subplot(1, 2, 1)
        axes.imshow(contrast_image.eval())

        axes = f.add_subplot(1, 2, 2)
        axes.imshow(random_contrast_image.eval())

        plt.show()


def hue_image(file):
    """
    色相调整
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.GFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    # 色相调整
    hue_image = tf.image.adjust_hue(img_data_jpg, 0.5)

    # 随机调整色相
    random_hue_image = tf.image.random_hue(img_data_jpg, 0.2)

    with tf.Session() as sess:
        f = plt.figure()
        axes = f.add_subplot(1, 2, 1)
        axes.imshow(hue_image.eval())

        axes = f.add_subplot(1, 2, 2)
        axes.imshow(random_hue_image.eval())

        plt.show()


def saturation_image(file):
    """
    设置图片饱和度
    :param file:
    :return:
    """
    image_raw_data = tf.gfile.GFile(file, 'rb').read()
    img_data_jpg = tf.image.decode_jpeg(image_raw_data)

    saturation_image = tf.image.adjust_saturation(img_data_jpg, 0.5)

    random_saturation_image = tf.image.random_saturation(img_data_jpg, 0.2, 0.5)

    with tf.Session() as sess:
        f = plt.figure()
        axes = f.add_subplot(1, 2, 1)
        axes.imshow(saturation_image.eval())

        axes = f.add_subplot(1, 2, 2)
        axes.imshow(random_saturation_image.eval())

        plt.show()






if __name__ == '__main__':
    # file_name = '../data/image/mnist.tfcord'
    # read_tfcord(file_name)

    saturation_image('../data/image/xg.jpg')
